package com.ibm.iisp.common.log;

import javax.persistence.EntityManager;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.DefaultTransactionDefinition;

import com.ibm.iisp.common.util.BeanFactory;

import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.core.UnsynchronizedAppenderBase;

public class LogbackJPAAppender extends UnsynchronizedAppenderBase<ILoggingEvent> {
	Logger log = LoggerFactory.getLogger(getClass());
	EntityManager em;

	@Override
	protected void append(ILoggingEvent eventObject) {
		if (em == null) {
			initDao();
		}
		Object[] args = eventObject.getArgumentArray();
		if (args == null || args.length == 0) {
			log.error("调用本Appender必须有一个参数！");
		} else {
			PlatformTransactionManager tm = BeanFactory.getInstance().getBean(PlatformTransactionManager.class);
			DefaultTransactionDefinition definition = new DefaultTransactionDefinition(TransactionDefinition.PROPAGATION_REQUIRES_NEW);
			TransactionStatus ts = tm.getTransaction(definition);
			for (Object arg : args) {
				em.persist(arg);
			}
			em.flush();
			tm.commit(ts);
		}
	}

	private void initDao() {
		em = BeanFactory.getInstance().getBean(EntityManager.class);
	}

}
